<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属支公司" prop="company">
        <el-select 
          v-model="queryParams.bmname" 
          placeholder="请选择所属支公司" 
          style="width:100%"
          @change="handleCompanyChange"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_dept_dept_name"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="光缆名称" prop="cableId">
        <el-select
          v-model="queryParams.cableId"
          filterable
          clearable
          placeholder="请选择光缆名称"
          style="width: 100%"
          :loading="loadingCables"
        >
          <el-option
            v-for="item in filteredCableOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务名称" prop="ywname">
        <el-input
          v-model="queryParams.ywname"
          placeholder="请输入业务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="炮筒名称" prop="ptname">
        <el-input
          v-model="queryParams.ptname"
          placeholder="请输入炮筒名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="源端口" prop="fromplace">
        <el-input
          v-model="queryParams.fromplace"
          placeholder="请输入源端口"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="宿端口" prop="toplace">
        <el-input
          v-model="queryParams.toplace"
          placeholder="请输入宿端口"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="距离" prop="height">
        <el-input
          v-model="queryParams.height"
          placeholder="请输入距离"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:realtest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:realtest:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete(selection)"
          v-hasPermi="['system:realtest:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:realtest:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:realtest:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="realtestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="部门名称" align="center" prop="bmname" />
      <el-table-column label="光缆名称" align="center" prop="glname" />
      <el-table-column label="业务名称" align="center" prop="ywname" />
      <!-- <el-table-column label="炮筒名称" align="center" prop="ptname" /> -->
      <el-table-column label="源端口（南海中心机房端）" align="center" prop="fromplace" />
      <el-table-column label="宿端口" align="center" prop="toplace" />
      <!-- <el-table-column label="距离" align="center" prop="height" /> -->
      <el-table-column label="纤芯状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.remarks" v-if='scope.row.remarks !== null && scope.row.remarks !=="" ' :width="50" :height="50"/>
          <p v-text="scope.row.remark" label="备注" prop="remark"></p>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:realtest:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:realtest:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入"xls"或"xlsx"格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改realtest对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="bmname">
              <el-select 
                v-model="form.bmname" 
                clearable 
                filterable 
                placeholder="请选择部门名称"
                @change="form.glname = ''"
              >
                <el-option
                  v-for="(dict,index) in dict.type.sys_dept_dept_name"
                  :key="index"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="光缆名称" prop="glname">
              <el-select 
                v-model="form.glname" 
                clearable 
                filterable 
                placeholder="请选择光缆名称"
                :disabled="!form.bmname"
              >
                <el-option
                  v-for="cable in filteredCableOptions"
                  :key="cable.id"
                  :label="cable.name"
                  :value="cable.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务名称" prop="ywname">
              <el-input v-model="form.ywname" placeholder="请输入业务名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="炮筒名称" prop="ptname">
              <el-input v-model="form.ptname" placeholder="请输入炮筒名称" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="源端口" prop="fromplace">
              <el-input v-model="form.fromplace" placeholder="请输入源端口" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宿端口" prop="toplace">
              <el-input v-model="form.toplace" placeholder="请输入宿端口" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="距离" prop="height">
          <el-input v-model="form.height" placeholder="请输入距离" />
        </el-form-item> -->
        <el-form-item label="备注">
          <image-upload v-model="form.remarks" @input="getImgUrl"/>
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCables, getCables, delCables, addCables, updateCables } from "@/api/system/cables";
import { listRealtest, getRealtest, delRealtest, addRealtest, updateRealtest, changeUserStatus, deptTreeSelect } from "@/api/system/realtest";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Realtest",
  dicts: ['sys_dept_dept_name'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // realtest表格数据
      realtestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bmname: null,
        glname: null,
        ywname: null,
        ptname: null,
        fromplace: null,
        toplace: null,
        height: null,
        status: null,
      },
      // 部门树选项
      deptOptions: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        glname: [
          { required: true, message: "光缆名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '光缆名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        ywname: [
          { required: true, message: "业务名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '业务名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/realtest/importData"
      },
      cableOptions: [],
      allCables: [], // 所有光缆数据
      filteredCableOptions: [], // 筛选后的光缆选项
      cableCompanyMap: new Map(), // 光缆ID到支公司的映射
      allCableOptions: [] // 所有光缆选项（用于表单）
    };
  },
  computed: {
    // 根据选择的部门筛选光缆选项
    filteredCableOptions() {
      if (!this.form.bmname) {
        return this.cableOptions;
      }
      
      // 找到部门对应的值
      const dept = this.dict.type.sys_dept_dept_name.find(
        d => d.label === this.form.bmname
      );
      
      if (!dept) return this.cableOptions;
      
      return this.cableOptions.filter(
        cable => cable.company === dept.value
      );
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getCables(); // 获取光缆名称
    this.loadAllCables();
  },
  methods: {
    /** 加载所有光缆数据 */
    loadAllCables() {
      this.loadingCables = true;
      listCables({ pageSize: 1000 }).then(response => {
        this.allCables = response.rows;
        // 建立映射关系
        response.rows.forEach(cable => {
          this.cableCompanyMap.set(cable.id, cable.company);
        });
        // 初始化所有选项
        this.allCableOptions = response.rows.map(cable => ({
          value: cable.id,
          label: cable.name
        }));
        this.filteredCableOptions = [...this.allCableOptions];
        this.loadingCables = false;
      }).catch(() => {
        this.loadingCables = false;
      });
    },

    /** 支公司选择变化时 */
    handleCompanyChange(company) {
      this.queryParams.cableId = null; // 清空已选光缆
      
      if (company) {
        // 筛选该支公司的光缆
        this.filteredCableOptions = this.allCables
          .filter(cable => cable.company === company)
          .map(cable => ({
            value: cable.id,
            label: cable.name
          }));
      } else {
        // 显示全部光缆
        this.filteredCableOptions = [...this.allCableOptions];
      }
    },
    getImgUrl(id, item) {
      this.form.remarks = item[0].url;
    },
    /** 查询realtest列表 */
    getList() {
      this.loading = true;
      listRealtest(this.queryParams).then(response => {
        this.realtestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取光缆列表 */
    getCables() {
      listCables({ pageSize: 10000 }).then(response => {
        this.cableOptions = response.rows.map(cable => ({
          id: cable.id,
          name: cable.name,
          company: cable.company
        }));
      }).catch(error => {
        console.error('获取光缆列表失败:', error);
        this.$message.error('获取光缆列表失败');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ywid: null,
        bmname: null,
        glname: null,
        ywname: null,
        ptname: null,
        fromplace: null,
        toplace: null,
        height: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        remarks: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ywid);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selection = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加realtest";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ywid = row.ywid || this.ids;
      getRealtest(ywid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改realtest";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保光缆名称是有效的
          if (this.form.glname && !this.cableOptions.some(c => c.name === this.form.glname)) {
            this.$message.warning('请选择有效的光缆名称');
            return;
          }
          
          if (this.form.ywid != null) {
            updateRealtest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRealtest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ywids = row.ywid || this.ids;
      if (row instanceof Array) {
        const rows = row.map(item => item.ywname);
        this.$modal.confirm('是否确认删除业务为"' + rows + '"的数据项？').then(function() {
          return delRealtest(ywids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      } else {
        this.$modal.confirm('是否确认删除业务为"' + row.ywname + '"的数据项？').then(function() {
          return delRealtest(ywids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/realtest/export', {
        ...this.queryParams
      }, `realtest_${new Date().getTime()}.xlsx`);
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要' + text + '' + row.ywid + '纤芯吗？').then(function() {
        return changeUserStatus(row.ywid, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "业务导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/realtest/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>